import EventCenter from "./event_center";
import TouchEvent from "./touch_event";
import ButtonState from "./button_state";
import Event from "./event";

export default class ButtonGroup {
  eachButton(e) {
    let t = this;
    for (let n = 0; n < t.buttons().length; n++) {
      let r = t.buttons()[n];
      if (e(n, r) === !1) break;
    }
  }
  _buttons = null;
  buttons() {
    let e = this;
    return e._buttons == null && (e._buttons = []), e._buttons;
  }
  addButtons(r) {
    let i = this;
    for (let s = 0; s < r.length; s++) {
      let o = r[s];
      o.switchMode(!0),
        o.buttonState(ButtonState.NORMAL_STATE),
        EventCenter.addListener(o, i, TouchEvent.TOUCH_END, i.onButtonTouchEnd),
        i.buttons().push(o);
    }
  }
  onButtonTouchEnd(t) {
    let n = this,
      i = t.target;
    n.selectButton(i), EventCenter.dispatchEvent(new Event(n, Event.CHANGE));
  }
  enable() {
    let e = this;
    e.eachButton(function (t, n) {
      n != e._selectedButton && n.enabled(!0);
    });
  }
  disable() {
    let e = this;
    e.eachButton(function (e, t) {
      t.enabled(!1);
    });
  }
  selectedIndex() {
    let e = this;
    return e.indexOfButton(e._selectedButton);
  }
  _selectedButton = null;
  selectedButton() {
    let e = this;
    return e._selectedButton;
  }
  buttonByIndex(e) {
    let t = this,
      n = null;
    return e >= 0 && e < t.buttons().length && (n = t.buttons()[e]), n;
  }
  indexOfButton(e) {
    let t = this,
      n = -1;
    for (let r = 0; r < t.buttons().length; r++)
      if (e == t.buttons()[r]) {
        n = r;
        break;
      }
    return n;
  }
  cancelable = !1;
  selectButton(e) {
    let t = this;
    if (t.cancelable) {
      t._selectedButton != null &&
        t._selectedButton.buttonState(ButtonState.NORMAL_STATE);
      let r = t._selectedButton;
      (t._selectedButton = null),
        r != e && (e.buttonState(ButtonState.CLICK_STATE), (t._selectedButton = e));
    } else
      t._selectedButton != null &&
        t._selectedButton != e &&
        (t._selectedButton.enabled(!0),
        t._selectedButton.buttonState(ButtonState.NORMAL_STATE)),
        e.buttonState(ButtonState.CLICK_STATE),
        e.enabled(!1),
        (t._selectedButton = e);
  }
  selectButtonByIndex(e) {
    let t = this,
      n = t.buttonByIndex(e);
    n != null && t.selectButton(n);
  }
  cancelSelect() {
    let e = this;
    e._selectedButton != null &&
      (e._selectedButton.enabled(!0),
      e._selectedButton.buttonState(ButtonState.NORMAL_STATE),
      (e._selectedButton = null));
  }
}
